import 'package:canteen/class/dish.dart';
import 'package:canteen/class/set_meal.dart';
import 'package:canteen/component/line_button.dart';
import 'package:canteen/dio/set_meal_dio.dart';
import 'package:canteen/menu_c_v.dart';
import 'package:canteen/method/find_by_name.dart';
import 'package:canteen/page/add_ingredient_page.dart';
import 'package:canteen/page/choose_page.dart';
import 'package:canteen/page/edit_line_page.dart';
import 'package:canteen/page/edit_set_meal_page.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:canteen/edit_c_v.dart';
import 'package:canteen/dio/dish_dio.dart';
import 'package:canteen/dio/configure_dio.dart';
import 'package:canteen/dio/category_dio.dart';
import 'package:canteen/method/showDialog.dart';

class EditMenuPage extends StatefulWidget {
  static String id = 'edit_menu_page';

  @override
  State<EditMenuPage> createState() => _EditMenuPageState();
}

class _EditMenuPageState extends State<EditMenuPage> {
  String title = '';
  late bool isCategory;
  late bool isAdd;
  String oldName = '';

  uploadData() async {
    if (name.isEmpty) {
      ShowDialog.showErrorAndDetail(context, '填写不能为空');
      return;
    }
    late Response response;
    if (!isCategory) {
      if (isAdd) {
        try {
          if (type == '单品') {
            response = await addDish(dish: {
              'name': name.trim(),
              'components': ingredientString,
              'categoryName': category,
            }, dio: dio);
            Dish newDish = Dish(
                name: name.trim(),
                components: dish.components,
                category: category,
                id: response.data['data']);
            dishesWithCategory[category]?.add(newDish);
            allDishes.add(newDish);
          } else {
            response = await addSetMeal(setMeal: {
              'categoryName': category,
              'name': name.trim(),
              "dishCount":
                  setMeal.dishes.map((key, value) => MapEntry(key.name, value))
            }, dio: dio);
            SetMeal newSetMeal = SetMeal(
                dishes: setMeal.dishes,
                name: name.trim(),
                category: category,
                id: response.data['data']);
            setMealsWithCategory[category]?.add(newSetMeal);
            allSetMeals.add(newSetMeal);
          }
          ShowDialog.showCorrectAndDetail(context, '上传成功');
        } on Exception catch (e) {
          print('add dish error');
          ShowDialog.showErrorAndDetail(context, '已存在');
        }
      } else {
        try {
          if (type == '单品') {
            response = await updateDish(dish: {
              'id': dish.id,
              'name': name,
              'components': ingredientString,
              'categoryName': category,
            }, dio: dio);
            int index = dishesWithCategory[dish.category]!
                .indexWhere((element) => element.id == dish.id);
            int index2 = allDishes.indexWhere((element) => element.id == dish.id);
            if (category != dish.category) {
              dishesWithCategory[category]?.add(Dish(
                  id: dish.id,
                  name: name,
                  components: dish.components,
                  category: category));
              dishesWithCategory[dish.category]?.removeAt(index);
            } else {
              dishesWithCategory[category]?[index]
                ?..name = name
                ..components = dish.components;
            }
            allDishes[index2]
              ..name = name
              ..components = dish.components
              ..category = category;
          } else {
            response = await updateSetMeal(setMeal: {
              'id': setMeal.id,
              'categoryName': category,
              'name': name.trim(),
              "dishCount":
                  setMeal.dishes.map((key, value) => MapEntry(key.name, value))
            }, dio: dio);
            int index = setMealsWithCategory[setMeal.category]!
                .indexWhere((element) => element.id == setMeal.id);
            int index2 =
                allSetMeals.indexWhere((element) => element.id == setMeal.id);
            if (category != setMeal.category) {
              setMealsWithCategory[setMeal.category]?.removeAt(index);
              setMealsWithCategory[category]?.add(SetMeal(
                  id: setMeal.id,
                  dishes: setMeal.dishes,
                  name: name,
                  category: category));
            } else {
              setMealsWithCategory[category]?[index]
                ?..dishes = setMeal.dishes
                ..name = name;
            }
            allSetMeals[index2]
              ..dishes = setMeal.dishes
              ..category = category
              ..name = name;
          }
          ShowDialog.showCorrectAndDetail(context, '上传成功');
        } on Exception catch (e) {
          print('update dish error');
        }
      }
    } else {
      if (isAdd) {
        try {
          response = await addCategory(category: {'name': name}, dio: dio);
          dishesWithCategory.addEntries([MapEntry(name, [])]);
          setMealsWithCategory.addEntries([MapEntry(name, [])]);
          categoryId.addEntries([MapEntry(name, response.data['data'])]);
          ShowDialog.showCorrectAndDetail(context, '上传成功');
        } on Exception catch (e) {
          print('add category error');
        }
      } else {
        try {
          response = await updateCategory(
              category: {'name': name, 'id': categoryId[oldName]!}, dio: dio);
          dishesWithCategory = dishesWithCategory
              .map((key, value) => MapEntry(key == oldName ? name : key, value));
          setMealsWithCategory = setMealsWithCategory
              .map((key, value) => MapEntry(key == oldName ? name : key, value));
          categoryId = categoryId
              .map((key, value) => MapEntry(key == oldName ? name : key, value));
          ShowDialog.showCorrectAndDetail(context, '上传成功');
        } on Exception catch (e) {
          print('update category error');
        }
      }
      sortedCategory = dishesWithCategory.keys.toList();
      sortedCategory.sort((a, b) => a.compareTo(b));
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    oldName = name;
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    final Map<String, dynamic>? args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    isCategory = args?['isCategory'] ?? false;
    isAdd = args?['isAdd'] ?? true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffafafa),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          isAdd ? '添加菜品' : '编辑菜品',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              uploadData();
            },
            child: Icon(
              Icons.save_outlined,
              color: Colors.black,
            ),
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 30),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(25),
                  topLeft: Radius.circular(25),
                ),
              ),
              child: Column(
                children: [
                  SizedBox(
                    height: 30,
                  ),
                  isCategory
                      ? SizedBox()
                      : AnimatedSwitcher(
                          duration: Duration(milliseconds: 200),
                          child: Row(
                            key: ValueKey(type),
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: ['单品', '套餐']
                                .map(
                                  (e) => GestureDetector(
                                    onTap: () {
                                      if (!isAdd) {
                                        return;
                                      }
                                      setState(() {
                                        type = e;
                                      });
                                    },
                                    child: Container(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 20, vertical: 10),
                                      decoration: BoxDecoration(
                                          color: type == e
                                              ? Color(0xff2b3db5)
                                                  .withOpacity(0.96)
                                              : Color(0xffd9d9d9)
                                                  .withOpacity(0.5),
                                          borderRadius:
                                              BorderRadius.circular(20)),
                                      child: Text(
                                        e,
                                        style: TextStyle(
                                            color: type == e
                                                ? Colors.white
                                                : Colors.black,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 20),
                                      ),
                                    ),
                                  ),
                                )
                                .toList(),
                          ),
                        ),
                  isCategory
                      ? SizedBox()
                      : Container(
                          height: 1,
                          color: Colors.black.withOpacity(0.2),
                          margin: EdgeInsets.symmetric(
                              horizontal: 50, vertical: 25),
                        ),
                  // isCategory
                  //     ? SizedBox()
                  //     : LineButton(
                  //         isSelect: true,
                  //         title: '分类',
                  //         content: Text(
                  //           type,
                  //           style: TextStyle(
                  //               color: Color(0xff2b3db5), fontSize: 16),
                  //           softWrap: true,
                  //         ),
                  //         onPressed: () {
                  //           options = ['单品', '套餐'];
                  //           if (!isAdd) {
                  //             return;
                  //           }
                  //           showModalBottomSheet(
                  //               context: context,
                  //               builder: (context) => ChoosePage()).then((_) {
                  //             setState(() {});
                  //           });
                  //         },
                  //       ),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(25),
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          offset: Offset(0, 1),
                          blurRadius: 2,
                          color: Colors.black.withOpacity(0.25),
                        )
                      ],
                    ),
                    child: Column(
                      children: [
                        Builder(
                          builder: (context) => LineButton(
                            title: '品名',
                            content: Text(
                              name,
                              style:
                                  TextStyle(color: Colors.black, fontSize: 16),
                              softWrap: true,
                            ),
                            onPressed: () {
                              setState(() {
                                title = '品名';
                              });
                              Navigator.pushNamed(context, EditLinePage.id,
                                  arguments: {
                                    'title': isCategory ? '品类' : '品名'
                                  }).then((value) {
                                setState(() {});
                              });
                            },
                          ),
                        ),
                        isCategory
                            ? SizedBox()
                            : LineButton(
                                isSelect: true,
                                title: '品类',
                                content: Text(
                                  category,
                                  style: TextStyle(
                                      color: Color(0xff2b3db5), fontSize: 16),
                                  softWrap: true,
                                ),
                                onPressed: () {
                                  options = dishesWithCategory.keys.toList();
                                  showModalBottomSheet(
                                          context: context,
                                          builder: (context) => ChoosePage())
                                      .then((_) {
                                    setState(() {});
                                  });
                                },
                              ),
                      ],
                    ),
                  ),
                  isCategory
                      ? SizedBox()
                      : AnimatedSwitcher(
                          duration: Duration(milliseconds: 200),
                          child: Builder(
                            key: ValueKey(type),
                            builder: (context) => LineButton(
                              title: type == '单品' ? '原料' : '菜品',
                              content: Icon(
                                Icons.arrow_forward_ios_rounded,
                                size: 18,
                              ),
                              onPressed: () {
                                setState(() {
                                  title = type == '单品' ? '原料' : '菜品';
                                });
                                Navigator.pushNamed(
                                        context,
                                        type == '单品'
                                            ? AddIngredientPage.id
                                            : EditSetMealPage.id)
                                    .then((value) {
                                  setState(() {});
                                });
                              },
                            ),
                          ),
                        ),
                  isCategory
                      ? SizedBox()
                      : Expanded(
                          child: type == '单品'
                              ? GridView.builder(
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisSpacing: 10,
                                    mainAxisSpacing: 10,
                                    crossAxisCount: 3,
                                  ),
                                  itemCount: dish.components.length,
                                  itemBuilder: (context, index) {
                                    var ingredientEntry = dish
                                        .components.entries
                                        .elementAt(index);
                                    return Container(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 5, horizontal: 8),
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(15),
                                          color: Colors.white,
                                          boxShadow: [
                                            BoxShadow(
                                              offset: Offset(0, 1),
                                              blurRadius: 2,
                                              color:
                                                  Colors.black.withOpacity(0.2),
                                            )
                                          ]),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          Row(
                                            children: [
                                              Text(
                                                '${ingredientEntry.key.name}',
                                                style: TextStyle(fontSize: 15),
                                              )
                                            ],
                                          ),
                                          Expanded(
                                            child: Row(
                                              children: [
                                                Container(
                                                  width: 2,
                                                  margin: EdgeInsets.only(
                                                      right: 8,
                                                      top: 6,
                                                      bottom: 4),
                                                  decoration: BoxDecoration(
                                                      color: Colors.black),
                                                ),
                                                Expanded(
                                                  child: Column(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .spaceEvenly,
                                                    children: [
                                                      Row(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .spaceBetween,
                                                        children: [
                                                          Text(
                                                            '类型',
                                                            style: TextStyle(
                                                                color:
                                                                    Colors.grey,
                                                                fontSize: 12),
                                                          ),
                                                          Text(
                                                            '${ingredientEntry.key.type}',
                                                            style: TextStyle(
                                                                color: Colors
                                                                    .black,
                                                                fontSize: 12),
                                                          )
                                                        ],
                                                      ),
                                                      Row(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .spaceBetween,
                                                        children: [
                                                          Text(
                                                            '数量',
                                                            style: TextStyle(
                                                                color:
                                                                    Colors.grey,
                                                                fontSize: 12),
                                                          ),
                                                          Text(
                                                            '${ingredientEntry.value.toString()}',
                                                            style: TextStyle(
                                                                color: Colors
                                                                    .black,
                                                                fontSize: 12),
                                                          )
                                                        ],
                                                      ),
                                                      Row(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .spaceBetween,
                                                        children: [
                                                          Text(
                                                            '单位',
                                                            style: TextStyle(
                                                                color:
                                                                    Colors.grey,
                                                                fontSize: 12),
                                                          ),
                                                          Text(
                                                            '${ingredientEntry.key.unit}',
                                                            style: TextStyle(
                                                                color: Colors
                                                                    .black,
                                                                fontSize: 12),
                                                          )
                                                        ],
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    );
                                  },
                                )
                              : GridView.builder(
                                  itemCount: setMeal.dishes.length,
                                  itemBuilder: (context, index) {
                                    return Stack(
                                      children: [
                                        Container(
                                          alignment: Alignment.center,
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 10, vertical: 8),
                                          decoration: BoxDecoration(
                                              boxShadow: [
                                                BoxShadow(
                                                    offset: Offset(0, 1),
                                                    blurRadius: 2,
                                                    color: Colors.black
                                                        .withOpacity(0.25))
                                              ],
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(15)),
                                          child: Text(
                                            setMeal.dishes.keys
                                                .map((e) => e.name)
                                                .toList()[index],
                                            style: TextStyle(fontSize: 16),
                                          ),
                                        ),
                                        Positioned(
                                          left: 8,
                                          top: 8,
                                          child: Container(
                                            height: 12,
                                            width: 12,
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              border: Border.all(
                                                  color: Colors.black
                                                      .withOpacity(0.6),
                                                  width: 0.5),
                                            ),
                                          ),
                                        ),
                                      ],
                                    );
                                    //   DishWidget(
                                    //   dishName: setMeal.dishes.keys
                                    //       .map((e) => e.name)
                                    //       .toList()[index],
                                    //   childWidget: Text(
                                    //       '×${setMeal.dishes.values.toList()[index]}'),
                                    // );
                                  },
                                  gridDelegate:
                                      SliverGridDelegateWithFixedCrossAxisCount(
                                    childAspectRatio: 2,
                                    crossAxisSpacing: 10,
                                    mainAxisSpacing: 10,
                                    crossAxisCount: 2,
                                  ),
                                ),
                        )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
// Container(
// margin: EdgeInsets.only(bottom: 15),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// MyButton(
// onClick: () {
// Navigator.pop(context);
// },
// child: Text(
// '返回',
// style: TextStyle(color: Colors.black, fontSize: 20),
// ),
// boxDecoration: BoxDecoration(
// boxShadow: [
// BoxShadow(
// color: Colors.black.withOpacity(0.1),
// offset: Offset(1, 4),
// blurRadius: 6,
// )
// ],
// color: Colors.white,
// borderRadius:
// BorderRadius.circular(20), // 设置圆角半径，你可以根据需要调整这个值
// ),
// size: [100, 45],
// ),
// MyButton(
// onClick: () {
//
// },
// boxDecoration: BoxDecoration(
// boxShadow: [
// BoxShadow(
// color: Colors.black.withOpacity(0.1),
// offset: Offset(1, 4),
// blurRadius: 6,
// )
// ],
// gradient: LinearGradient(
// begin: Alignment.topLeft,
// end: Alignment.bottomRight,
// colors: [
// Color(0xff94F8FF),
// Color(0xffB6C4FF),
// Color(0xffF7D1FF),
// Color(0xffFFE1BE),
// ].map((e) => e.withOpacity(0.6)).toList()),
// borderRadius:
// BorderRadius.circular(20), // 设置圆角半径，你可以根据需要调整这个值
// ),
// child: Text(
// isAdd ? '添加' : '修改',
// style: TextStyle(color: Colors.white, fontSize: 20),
// ),
// size: [100, 45],
// )
// ],
// ),
// )
